<template>
  <div :bordered="false">
    <a-row :gutter="16">
      <a-col :span="8">
        <a-button type="primary" @click="showAddModal = true">添加用户</a-button>
      </a-col>
    </a-row>

    <a-table
      class="width:100%;"
      :columns="columns"
      :data-source="filteredUsers"
      :pagination="pagination"
      @change="handleTableChange"
    >
      <template slot="action" slot-scope="text, record">
        <a @click="edit(record)">编辑</a>
        <a-divider type="vertical" />
        <a-popconfirm title="确定要删除该用户吗？" @confirm="() => deleteRecord(record.id)">
          <a>删除</a>
        </a-popconfirm>
      </template>
    </a-table>

    <a-modal v-model="showAddModal" title="添加用户" @ok="handleAdd" @cancel="handleCancel">
      <a-form :form="form">
        <a-form-item label="姓名" :labelCol="{ span: 7 }" :wrapperCol="{ span: 17 }">
          <a-input v-decorator="['mangerName', { rules: [{ required: true, message: '请输入姓名！' }] }]" />
        </a-form-item>
        <a-form-item label="性别" :labelCol="{ span: 7 }" :wrapperCol="{ span: 17 }">
          <a-radio-group
            v-decorator="['mangerSex', { initialValue: '男', rules: [{ required: true, message: '请选择性别！' }] }]"
          >
            <a-radio value="男">男</a-radio>
            <a-radio value="女">女</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="联系电话" :labelCol="{ span: 7 }" :wrapperCol="{ span: 17 }">
          <a-input v-decorator="['mangerPhone', { rules: [{ required: true, message: '请输入联系电话！' }] }]" />
        </a-form-item>
        <a-form-item label="类别" :labelCol="{ span: 7 }" :wrapperCol="{ span: 17 }">
          <a-select
            :options="legal_type['project_user_type']"
            v-decorator="['mangerType', { rules: [{ required: true, message: '请选择类别！' }] }]"
          >
          </a-select>
        </a-form-item>
        <a-form-item label="职务" :labelCol="{ span: 7 }" :wrapperCol="{ span: 17 }">
          <a-input v-decorator="['mangerPost', { rules: [{ required: true, message: '请输入职务！' }] }]" />
        </a-form-item>
        <a-form-item label="出生年月" :labelCol="{ span: 7 }" :wrapperCol="{ span: 17 }">
          <a-date-picker
            v-decorator="['mangerBirthday', { rules: [{ required: true, message: '请选择出生年月！' }] }]"
            format="YYYY-MM-DD"
          />
        </a-form-item>
        <a-form-item label="身份证" :labelCol="{ span: 7 }" :wrapperCol="{ span: 17 }">
          <a-input v-decorator="['card', { rules: [{ required: true, message: '请输入身份证号！' }] }]" />
        </a-form-item>
        <a-form-item label="所属部门" :labelCol="{ span: 7 }" :wrapperCol="{ span: 17 }">
          <a-input v-decorator="['dept', { rules: [{ required: true, message: '请输入所属部门！' }] }]" />
        </a-form-item>
        <a-form-item label="本单位工作开始时间" :labelCol="{ span: 7 }" :wrapperCol="{ span: 17 }">
          <a-date-picker
            v-decorator="[
              'employmentStartDate',
              { rules: [{ required: true, message: '请选择本单位工作开始时间！' }] },
            ]"
            format="YYYY-MM-DD"
          />
        </a-form-item>
        <a-form-item label="从业开始时间" :labelCol="{ span: 7 }" :wrapperCol="{ span: 17 }">
          <a-date-picker
            v-decorator="['workStartDate', { rules: [{ required: true, message: '请选择从业开始时间！' }] }]"
            format="YYYY-MM-DD"
          />
        </a-form-item>
        <a-form-item label="毕业院校" :labelCol="{ span: 7 }" :wrapperCol="{ span: 17 }">
          <a-input v-decorator="['graduateSchool', { rules: [{ required: true, message: '请输入毕业院校！' }] }]" />
        </a-form-item>
        <a-form-item label="最高学历" :labelCol="{ span: 7 }" :wrapperCol="{ span: 17 }">
          <a-input v-decorator="['highestEducation', { rules: [{ required: true, message: '请输入最高学历！' }] }]" />
        </a-form-item>
        <a-form-item label="主体代码" :labelCol="{ span: 7 }" :wrapperCol="{ span: 17 }">
          <a-input v-decorator="['legalCode', { rules: [{ required: true, message: '请输入主体代码！' }] }]" />
        </a-form-item>
        <a-form-item label="社会保险号" :labelCol="{ span: 7 }" :wrapperCol="{ span: 17 }">
          <a-input
            v-decorator="['socialSecurityNumber', { rules: [{ required: true, message: '请输入社会保险号！' }] }]"
          />
        </a-form-item>
        <a-form-item label="职称编号" :labelCol="{ span: 7 }" :wrapperCol="{ span: 17 }">
          <a-input v-decorator="['titleCode', { rules: [{ required: true, message: '请输入职称编号！' }] }]" />
        </a-form-item>
        <a-form-item label="职称" :labelCol="{ span: 7 }" :wrapperCol="{ span: 17 }">
          <a-input v-decorator="['titleName', { rules: [{ required: true, message: '请输入职称！' }] }]" />
        </a-form-item>
        <a-form-item label="从业经历" :labelCol="{ span: 7 }" :wrapperCol="{ span: 17 }">
          <a-textarea
            v-decorator="['workHistory', { rules: [{ required: false, message: '请输入从业经历！' }] }]"
            placeholder="请输入从业经历！"
            :autosize="{ minRows: 3, maxRows: 5 }"
          />
        </a-form-item>
      </a-form>
    </a-modal>

    <a-modal v-model="showEditModal" title="编辑用户" @ok="handleEdit" @cancel="handleCancel">
      <a-form :form="form">
        <a-form-item label="姓名" :labelCol="{ span: 7 }" :wrapperCol="{ span: 17 }">
          <a-input v-decorator="['mangerName', { rules: [{ required: true, message: '请输入姓名！' }] }]" />
        </a-form-item>
        <a-form-item label="性别" :labelCol="{ span: 7 }" :wrapperCol="{ span: 17 }">
          <a-radio-group
            v-decorator="['mangerSex', { initialValue: '男', rules: [{ required: true, message: '请选择性别！' }] }]"
          >
            <a-radio value="男">男</a-radio>
            <a-radio value="女">女</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="联系电话" :labelCol="{ span: 7 }" :wrapperCol="{ span: 17 }">
          <a-input v-decorator="['mangerPhone', { rules: [{ required: true, message: '请输入联系电话！' }] }]" />
        </a-form-item>
        <a-form-item label="类别" :labelCol="{ span: 7 }" :wrapperCol="{ span: 17 }">
          <a-select
            :options="legal_type['project_user_type']"
            v-decorator="['mangerType', { rules: [{ required: true, message: '请选择类别！' }] }]"
          >
          </a-select>
        </a-form-item>
        <a-form-item label="职务" :labelCol="{ span: 7 }" :wrapperCol="{ span: 17 }">
          <a-input v-decorator="['mangerPost', { rules: [{ required: true, message: '请输入职务！' }] }]" />
        </a-form-item>
        <a-form-item label="出生年月" :labelCol="{ span: 7 }" :wrapperCol="{ span: 17 }">
          <a-date-picker
            v-decorator="['mangerBirthday', { rules: [{ required: true, message: '请选择出生年月！' }] }]"
            format="YYYY-MM-DD"
          />
        </a-form-item>
        <a-form-item label="身份证" :labelCol="{ span: 7 }" :wrapperCol="{ span: 17 }">
          <a-input v-decorator="['card', { rules: [{ required: true, message: '请输入身份证号！' }] }]" />
        </a-form-item>
        <a-form-item label="所属部门" :labelCol="{ span: 7 }" :wrapperCol="{ span: 17 }">
          <a-input v-decorator="['dept', { rules: [{ required: true, message: '请输入所属部门！' }] }]" />
        </a-form-item>
        <a-form-item label="本单位工作开始时间" :labelCol="{ span: 7 }" :wrapperCol="{ span: 17 }">
          <a-date-picker
            v-decorator="[
              'employmentStartDate',
              { rules: [{ required: true, message: '请选择本单位工作开始时间！' }] },
            ]"
            format="YYYY-MM-DD"
          />
        </a-form-item>
        <a-form-item label="从业开始时间" :labelCol="{ span: 7 }" :wrapperCol="{ span: 17 }">
          <a-date-picker
            v-decorator="['workStartDate', { rules: [{ required: true, message: '请选择从业开始时间！' }] }]"
            format="YYYY-MM-DD"
          />
        </a-form-item>
        <a-form-item label="毕业院校" :labelCol="{ span: 7 }" :wrapperCol="{ span: 17 }">
          <a-input v-decorator="['graduateSchool', { rules: [{ required: true, message: '请输入毕业院校！' }] }]" />
        </a-form-item>
        <a-form-item label="最高学历" :labelCol="{ span: 7 }" :wrapperCol="{ span: 17 }">
          <a-input v-decorator="['highestEducation', { rules: [{ required: true, message: '请输入最高学历！' }] }]" />
        </a-form-item>
        <a-form-item label="主体代码" :labelCol="{ span: 7 }" :wrapperCol="{ span: 17 }">
          <a-input v-decorator="['legalCode', { rules: [{ required: true, message: '请输入主体代码！' }] }]" />
        </a-form-item>
        <a-form-item label="社会保险号" :labelCol="{ span: 7 }" :wrapperCol="{ span: 17 }">
          <a-input
            v-decorator="['socialSecurityNumber', { rules: [{ required: true, message: '请输入社会保险号！' }] }]"
          />
        </a-form-item>
        <a-form-item label="职称编号" :labelCol="{ span: 7 }" :wrapperCol="{ span: 17 }">
          <a-input v-decorator="['titleCode', { rules: [{ required: true, message: '请输入职称编号！' }] }]" />
        </a-form-item>
        <a-form-item label="职称" :labelCol="{ span: 7 }" :wrapperCol="{ span: 17 }">
          <a-input v-decorator="['titleName', { rules: [{ required: true, message: '请输入职称！' }] }]" />
        </a-form-item>
        <a-form-item label="从业经历" :labelCol="{ span: 7 }" :wrapperCol="{ span: 17 }">
          <a-textarea
            v-decorator="['workHistory', { rules: [{ required: false, message: '请输入从业经历！' }] }]"
            placeholder="请输入从业经历！"
            :autosize="{ minRows: 3, maxRows: 5 }"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script>
import {
  Modal,
  Button,
  Input,
  Table,
  Form,
  Row,
  Col,
  Popconfirm,
  Divider,
  Card,
  InputSearch,
  Select,
  Option,
  DatePicker,
} from 'ant-design-vue'
import { axios } from '@/utils/request'
import { mapGetters } from 'vuex'
import { tableMixin, tableImgMixin } from './mixin'
const { Column } = Table
const { Item: FormItem } = Form

export default {
  name: 'UserManager',
  components: {},
  mixins: [tableMixin, tableImgMixin],
  data() {
    return {
      searchText: '',
      showAddModal: false,
      showEditModal: false,
      users: [],
      filteredUsers: [],
      currentRow: null,
      legal_type: {},
      form: this.$form.createForm(this, { name: 'user' }),
    }
  },
  computed: {
    ...mapGetters(['userInfo']),
    columns() {
      return [
        { title: '姓名', dataIndex: 'mangerName', key: 'mangerName' },
        { title: '性别', dataIndex: 'mangerSex', key: 'mangerSex' },
        { title: '身份证', dataIndex: 'card', key: 'card' },
        { title: '联系电话', dataIndex: 'mangerPhone', key: 'mangerPhone' },
        {
          title: '类别',
          dataIndex: 'mangerType',
          key: 'mangerType',
          customRender: text => this.legal_type['project_user_type']?.find(v => v.value == text)?.label ?? text,
        },
        {
          title: '职务',
          dataIndex: 'mangerPost',
          key: 'mangerPost',
        },
        { title: '操作', key: 'action', scopedSlots: { customRender: 'action' } },
      ]
    },
  },
  props: {
    canFix: {
      type: Boolean,
    },
    // 基本类型检查 (`null` 和 `undefined` 会通过任何类型验证)
    legalCode: String,
  },
  methods: {
    getUserType(userType) {
      this.$http.get('/register/common/getDictItems/' + userType).then(r => {
        this.$set(this.legal_type, userType, r.result)
      })
    },
    async getData() {
      try {
        const response = await axios.get('/register/subjectLegalManager/list', {
          params: { legalCode: this.legalCode, pageSize: this.pagination.pageSize, pageNo: this.pagination.current },
        })
        this.users = response.result.records
        this.filteredUsers = response.result.records
        this.pagination.total = response.result.total
      } catch (error) {
        console.error('获取用户列表失败:', error)
      }
    },
    onSearch(value) {
      this.searchText = value
      this.filteredUsers = this.users.filter(
        user =>
          user.mangerName.toLowerCase().includes(value.toLowerCase()) ||
          user.mangerPhone.toLowerCase().includes(value.toLowerCase()),
      )
    },

    edit(record) {
      this.currentRow = record
      this.showEditModal = true
      this.$nextTick(() => {
        this.form.setFieldsValue(this.currentRow)
      })
    },
    deleteRecord(id) {
      axios
        .delete(`/register/subjectLegalManager/delete?id${id}`)
        .then(() => {
          this.getData()
        })
        .catch(error => {
          console.error('删除用户失败:', error)
        })
    },
    handleAdd() {
      this.form.validateFields((err, values) => {
        if (!err) {
          values.legalCode = this.legalCode
          axios
            .post('/register/subjectLegalManager/add', values)
            .then(() => {
              this.showAddModal = false
              this.getData()
            })
            .catch(error => {
              console.error('添加用户失败:', error)
            })
        }
      })
    },
    handleEdit() {
      this.form.validateFields((err, values) => {
        if (!err) {
          values.legalCode = this.legalCode
          values.id = this.currentRow.id
          axios
            .put(`/register/subjectLegalManager/edit`, values)
            .then(() => {
              this.showEditModal = false
              this.getData()
            })
            .catch(error => {
              console.error('更新用户失败:', error)
            })
        }
      })
    },
    handleCancel() {
      this.showAddModal = false
      this.showEditModal = false
      this.form.resetFields()
    },
  },
  mounted() {
    this.getData()
    this.getUserType('project_user_type')
  },
}
</script>

<style scoped>
/* Add your styles here */
</style>
